﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace XmlSerializationDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.Name = "peter";
            person.Age = 29;

            var personString = XmlSerialize<Person>(person);
            Console.WriteLine(personString);
            var newPserson = XmlDeserialize<Person>(personString);

            AnotherPerson person1 = new AnotherPerson();
            person1.Name = "peter";
            person1.Age = 29;

            var personString1 = XmlSerialize<AnotherPerson>(person1);
            Console.WriteLine(personString1);
            var newPserson1 = XmlDeserialize<AnotherPerson>(personString1);

            Console.ReadLine();

        }

        public static string XmlSerialize<T>(T obj)
        {
            string xmlString = string.Empty;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                xmlSerializer.Serialize(ms, obj);
                xmlString = Encoding.UTF8.GetString(ms.ToArray());
            }
            return xmlString;
        }

        public static T XmlDeserialize<T>(string xmlString)
        {
            T t = default(T);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
            {
                using (XmlReader xmlReader = XmlReader.Create(xmlStream))
                {
                    Object obj = xmlSerializer.Deserialize(xmlReader);
                    t = (T)obj;
                }
            }
            return t;
        }
    }
}
